//
//  MicView.m
//  MooreDoll
//
//  Created by Joe on 2014/12/18.
//  Copyright (c) 2014年 Tank. All rights reserved.
//

#import "MicView.h"
#import <CoreMedia/CoreMedia.h>
#import <AVFoundation/AVFoundation.h>
#include "libxclient.h"
#include "lame.h"

@implementation MicView
{
    CGFloat         sampleRate ;
    NSInteger       formatIndex ;
    AVAudioQuality  quality ;
    NSInteger       channel ;
    NSURL           *recordedFileUrl;
    AVAudioRecorder *recorder;
    BOOL            hasCAFFile;
    NSString        *g_mp3FilePath;
    BOOL            hasMp3File;
    
    NSArray         *voiceMode;
    NSArray         *playMode;
    
}
@synthesize BT_playMode,BT_voiceMode;


-(void)microphoneSetting
{
    
    voiceMode = @[];
    
    gest_longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(microphonePress:)];
    [BT_microphone addGestureRecognizer:gest_longPress];
    self.backgroundColor = [UIColor whiteColor];
    
    voiceMode = @[@"原聲",@"機器人",@"男聲",@"女聲",@"Ghost"];
    playMode  = @[@"直接播放",@"喚醒時播放",@"娃娃被抱起時播",@"預約時間播"];
    BT_playMode.titleLabel.text = [playMode objectAtIndex:0];
    BT_voiceMode.titleLabel.text = [voiceMode objectAtIndex:0];
    
    // init pickView
    pickView_playMode            = [[UIPickerView alloc] initWithFrame:CGRectMake(0,
                                                                                  self.frame.size.height,
                                                                                  self.frame.size.width,
                                                                                  self.frame.size.height)];
    pickView_playMode.delegate   = self;
    pickView_playMode.dataSource = self;
    [pickView_playMode reloadAllComponents];
    pickView_playMode.backgroundColor = [UIColor whiteColor];
    [self addSubview:pickView_playMode];
    
    pickView_voiceMode           = [[UIPickerView alloc] initWithFrame:CGRectMake(0,
                                                                                  self.frame.size.height,
                                                                                  self.frame.size.width,
                                                                                  self.frame.size.height)];
    pickView_voiceMode.delegate  = self;
    pickView_voiceMode.dataSource= self;
    [pickView_voiceMode reloadAllComponents];
    pickView_voiceMode.backgroundColor = [UIColor whiteColor];
    [self addSubview:pickView_voiceMode];
    
    
}


-(void)microphonePress:(UILongPressGestureRecognizer *)longPress
{

    if (longPress.state == UIGestureRecognizerStateBegan)
    {
        //開始錄音
        NSLog(@"start record");
        NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
                                  [NSNumber numberWithFloat: 44100.0],                  AVSampleRateKey,
                                  [NSNumber numberWithInt: kAudioFormatLinearPCM],                   AVFormatIDKey,
                                  [NSNumber numberWithInt: 2],                              AVNumberOfChannelsKey,
                                  [NSNumber numberWithInt: 0x40],                       AVEncoderAudioQualityKey,
                                  nil];
        
        //set file name
        NSDateFormatter *dateFormate = [[NSDateFormatter alloc] init];
        [dateFormate setDateFormat:@"YY-MM-dd-e_HH_mm-ss"];
        NSString *dateString = [dateFormate stringFromDate:[NSDate date]];
        NSString *fileName = [[NSString alloc] initWithFormat:@"recordto_%@.caf",dateString];
        
        
        // set file path
        recordFilePath       = [NSTemporaryDirectory() stringByAppendingString:[[NSString alloc] initWithFormat:@"%@",fileName]];
        recordedFileUrl      = [NSURL fileURLWithPath:recordFilePath];
        
        // init Recorder
        NSError *error;
        recorder = [[AVAudioRecorder alloc] initWithURL:recordedFileUrl
                                               settings:settings
                                                  error:&error];
        if (error)
        {
            NSLog(@"%@", [error description]);
            return;
        }
        else
        {
            #warning Patrick Record error
            [recorder prepareToRecord];
            [[AVAudioSession sharedInstance]setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
            [recorder record];
        }
 
    }
    else if(longPress.state == UIGestureRecognizerStateEnded)
    {
        NSLog(@"stop record");
        [recorder stop];
        
        [self ConvertToMp3WithCafPath:recordFilePath];
        
        recorder        = nil;
        recordedFileUrl = nil;
        recordFilePath  = nil;
    }
    
}


-(IBAction)voiceStatusButtonPress:(UIButton *)sender
{
    [UIView animateWithDuration:0.5 animations:
     ^{
         [pickView_voiceMode setFrame:CGRectMake(0,
                                                 0,
                                                 pickView_voiceMode.frame.size.width,
                                                 pickView_voiceMode.frame.size.height)];
     }];
}

-(IBAction)playModeButtonPress:(UIButton *)sender
{
    [UIView animateWithDuration:0.5 animations:
     ^{
        [pickView_playMode setFrame:CGRectMake(0,
                                               0,
                                               pickView_playMode.frame.size.width,
                                               pickView_playMode.frame.size.height)];
    }];
}


-(void)ConvertToMp3WithCafPath:(NSString *)cafPath
{
    
    //錄音檔原始路徑
    NSString *cafFilePath = recordFilePath;
    
    //設定檔名，用日期命名
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YY-MM-dd-e_HH_mm-ss"];
    NSString *mp3FileName = [NSString stringWithFormat:@"recordto_%@.mp3",[dateFormatter stringFromDate:date]];
    //NSString *mp3FileName = [@"recordto_" stringByAppendingString:[dateFormatter stringFromDate:date]];
    
    // set outPut file name
    NSString *mp3FilePathInApp = [[NSString alloc] initWithFormat:@"/Documents/record/%@",mp3FileName];
    NSString *mp3FilePath = [NSHomeDirectory() stringByAppendingString:mp3FilePathInApp];
    
    
    
    @try {
        int read, write;
        
        FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb");  //source
        fseek(pcm, 4*1024, SEEK_CUR);                                   //skip file header
        FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");  //output
        
        const int PCM_SIZE = 8192;
        const int MP3_SIZE = 8192;
        short int pcm_buffer[PCM_SIZE*2];
        unsigned char mp3_buffer[MP3_SIZE];
        
        lame_t lame = lame_init();
        lame_set_in_samplerate(lame, 44100.0);
        lame_set_VBR(lame, vbr_default);
        lame_init_params(lame);
        
        do
        {
            read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
            if (read == 0)
                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
            else
                write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
            
            fwrite(mp3_buffer, write, 1, mp3);
            
        } while (read != 0);
        
        lame_close(lame);
        fclose(mp3);
        fclose(pcm);
    }
    @catch (NSException *exception)
    {
        NSLog(@"%@",[exception description]);
    }
    @finally
    {
        [self.delegate sendAudioToXMPPWithDataPath:mp3FilePath andFileName:mp3FileName andPathInApp:mp3FilePathInApp];
        NSLog(@"file's size : %d",[self getFileSize:mp3FilePath]);
    }

    

}

- (NSInteger) getFileSize:(NSString*) path
{
    NSFileManager * filemanager = [[NSFileManager alloc]init];
    if([filemanager fileExistsAtPath:path])
    {
        NSDictionary * attributes = [filemanager attributesOfItemAtPath:path error:nil];
        NSNumber *theFileSize;
        if ( (theFileSize = [attributes objectForKey:NSFileSize]) )
            return  [theFileSize intValue];
        else
            return -1;
    }
    else
        return -1;
    
}

#pragma mark UIPickViewDataSource and UIPickViewDelegate

- (int)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (int)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (pickerView == pickView_playMode)
        return playMode.count;
    else
        return voiceMode.count;
    
}

- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (pickerView == pickView_playMode)
        return [playMode objectAtIndex:row];
    else
        return [voiceMode objectAtIndex:row];
    
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    if (pickerView == pickView_playMode)
        BT_playMode.titleLabel.text = [playMode objectAtIndex:row];
    else
        BT_voiceMode.titleLabel.text = [voiceMode objectAtIndex:row];
    
    [UIView animateWithDuration:0.5 animations:
     ^{
         if (pickerView == pickView_playMode)
            pickView_playMode.frame = CGRectMake(0,
                                                 self.frame.size.height,
                                                 pickView_playMode.frame.size.width,
                                                 pickView_playMode.frame.size.height);
         else
             pickView_voiceMode.frame = CGRectMake(0,
                                                   self.frame.size.height,
                                                   pickView_voiceMode.frame.size.width,
                                                   pickView_voiceMode.frame.size.height);
     }];
}

@end
